package com.smartum.mpr.dao;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.smartum.mpr.exception.DatabaseIntegrityException;
import com.smartum.mpr.exception.NotCorrectPermission;
import com.smartum.mpr.exception.NotExistsOddException;
import com.smartum.mpr.model.Odd;
import com.smartum.mpr.model.UploadedImageOdd;

@Repository
public class UploadedImageOddDao extends GenericDao<Long, UploadedImageOdd> {


	public Odd getOdd(Long userId, Long imageId) throws NotExistsOddException, DatabaseIntegrityException{
		DetachedCriteria criteria = DetachedCriteria.forClass(UploadedImageOdd.class);
		criteria.createCriteria("user").add(Restrictions.eq("id", userId));
		criteria.createCriteria("image").add(Restrictions.eq("id", imageId));

		List odds = hibernateTemplate.findByCriteria(criteria);

		if (odds.size() == 0) {
			throw new NotExistsOddException();
		} else if (odds.size() > 1) {
			throw new DatabaseIntegrityException("database has few equals odds");
		} else if (odds.size() == 1) {
			return (Odd) odds.get(0);
		} else {
			throw new DatabaseIntegrityException();
		}
	}


	@Override
	protected Class<UploadedImageOdd> getEntityClass() {
		return UploadedImageOdd.class;
	}

}
